package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 逻辑过期
     * @param key
     * @param value
     * @param time
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        //设置逻辑过期对象
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值解决缓存击穿
     * @param keyProfix
     * @param id
     * @param type 缓存对象类型
     * @param dbFallback 函数式接口
     * @param time
     * @param unit
     * @return
     * @param <R>
     * @param <ID>
     */
    public  <R,ID> R queryShopWithThrough
    (String keyProfix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit){
        //1. 查询缓存
        String key = keyProfix + id;
        String Json = stringRedisTemplate.opsForValue().get(key);

        //2. 判断是否存在
        if(StrUtil.isNotBlank(Json)){
            return JSONUtil.toBean(Json, type);
        }
        //2.1 判断是否为空
        if(Json != null){
            return null;
        }

        //3. 未命中，查询数据库
        //3.1 判断数据库是否存在
        R r = dbFallback.apply(id);

        //3.2 不存在，记录key值，写入空字符串
        if(r == null){
            //3.3 将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }

        //4. 存在，写入缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r));

        //4.1 设置过期时间
        this.set(key, r, time, unit);

        return r;
    }

    //创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //缓存逻辑过期
    public <R,ID> R queryShopWithLogicalExpire
    (String keyProfix, ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit) {
        String key = keyProfix + id;
        //1. 从redis查询
        String Json = stringRedisTemplate.opsForValue().get(key);

        //2. 判断是否存在
        if(StrUtil.isBlank(Json)){
            //3. 不存在，直接返回
            return null;
        }
        //4. 存在，先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //5. 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            //5.1 未过期，直接返回
            return r;
        }
        //5.2 已过期，实现缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        //6.1 获取锁
        boolean tryLock = tryLock(lockKey);

        //6.2 判断是否获取成功
        if(tryLock){
            //6.3 判断缓存是否过期
            Json = stringRedisTemplate.opsForValue().get(key);

            //2. 判断是否存在
            if(StrUtil.isBlank(Json)){
                //3. 不存在，直接返回
                return null;
            }
            //4. 存在，先把json反序列化为对象
            redisData = JSONUtil.toBean(Json, RedisData.class);
            r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
            expireTime = redisData.getExpireTime();

            //5. 判断是否过期
            if(expireTime.isAfter(LocalDateTime.now())){
                //5.1 未过期，直接返回
                return r;
            }

            //6.4 获取锁成功，开启独立线程实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //写入缓存
                    this.setWithLogicalExpire(key, r1, time, unit);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });

        }

        //6.5 返回过期的数据
        return r;

    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//使用hutool工具类转换，防止空指针异常
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
